/* internal/js/delivery/maintain.js */

/* Common */

var SERVLET_PATH = '/ordrs/internal/maintain-delivery'; 

/* END Common */


/* Create */

function createDelivery () {
	createDeliveryValidate();
}

//done
function createDeliveryValidate () {
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var address = document.getElementById('address').value;
	var city = document.getElementById('city').value;
	var province = document.getElementById('province').value;
	var postalCode = document.getElementById('postalCode1').value + 
					document.getElementById('postalCode2').value;
	var instruction = document.getElementById('instruction').value;
	var dwelling = document.getElementById('dwellingType').options[document.getElementById('dwellingType').selectedIndex].value;
	var status = document.getElementById('deliveryStatus').options[document.getElementById('deliveryStatus').selectedIndex].value;
	var orderID = document.getElementById('orderID').value;
	var building;
	var room;
	
	if (dwelling == 'Hotel' || dwelling == 'Apartment') {
		building = document.getElementById('building').value;
		room = document.getElementById('room').value;
	}
	else if (dwelling == 'Company Building') {
		building = document.getElementById('building').value;
		room = null;
	}
	else {
		building = null;
		room = null;
	}
	var valid = true;

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');
	/*
	if (lastname == '') { //left blank
		valid = false;
		showFieldRequired('lastnameMessage');
	}*/

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}
	else if (!isNumeric(phone)) {
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}
	else
		hideFieldMessage('phoneMessage');

	if (address == '') { //left blank
		valid = false;
		showFieldRequired('addressMessage');
	}
	else
		hideFieldMessage('addressMessage');
	
	if (city == '') { //left blank
		valid = false;
		showFieldRequired('cityMessage');
	}
	else
		hideFieldMessage('cityMessage');
	
	if (province == '') { //left blank
		valid = false;
		showFieldRequired('provinceMessage');
	}
	else
		hideFieldMessage('provinceMessage');

	if (dwelling == '') { //left blank
		valid = false;
		showFieldRequired('dwellingTypeMessage');
	}
	else
		hideFieldMessage('dwellingTypeMessage');

	//todo postalcode format check
	
	if (valid)
		createDeliverySend(firstname, lastname, phone, address, city, province, postalCode, dwelling, building, room, status, instruction, orderID);
}

//done
function createDeliverySend (firstname, lastname, phone, address, city, province, postalCode, dwelling, building, room, status, instruction, orderID) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('c') +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&address=' + encodeURI(address) +
	            '&city=' + encodeURI(city) +
	            '&province=' + encodeURI(province) +
	            '&postal=' + encodeURI(postalCode) +
	            '&dwelling=' + encodeURI(dwelling) +
	            '&building=' + encodeURI(building) +
	            '&room=' + encodeURI(room) +
	            '&status=' + encodeURI(status) +
	            '&instruction=' + encodeURI(instruction) +
	            '&orderid=' + encodeURI(orderID);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				createDeliveryReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				createDeliveryReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}

function createDeliveryReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		listAllDeliverySend();
		showDialog('New delivery created.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Create */


/* Report */

function reportDelivery (deliveryID) {
	reportDeliveryValidate(deliveryID);
}

//done
function reportDeliveryValidate (deliveryID) {
	try {
		deliveryID.length;
	} catch(e){
		deliveryID = '';
	}
	if (deliveryID == '') {
		var firstname = document.getElementById('firstname').value;
		var lastname = document.getElementById('lastname').value;
		var phone = document.getElementById('phone').value;
	}
	else{
		firstname = '';
		lastname = '';
		phone = '';
	}

	reportDeliverySend(deliveryID, firstname, lastname, phone);
}

//done
function reportDeliverySend (deliveryID, firstname, lastname, phone) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('r') +
				'&id=' + encodeURI(deliveryID) +
				'&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
		        '&phone=' + encodeURI(phone);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				reportDeliveryReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				reportDeliveryReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function reportDeliveryReceive (xml) {
	if (xml.getElementsByTagName('deliveries').length > 0) {
		var deliveries = xml.getElementsByTagName('deliveries')[0];
		showResults(buildTable(deliveries));
		if (deliveries.childNodes.length == 1)
		{
			showResult(deliveries.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10101)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END Report*/


/* Update */

function updateDelivery () {
	updateDeliveryValidate();
}

function updateDeliveryValidate () {
	var id = document.getElementById('deliveryID').value;
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var address = document.getElementById('address').value;
	var city = document.getElementById('city').value;
	var province = document.getElementById('province').value;
	var postalCode = document.getElementById('postalCode1').value + 
					document.getElementById('postalCode2').value;
	var instruction = document.getElementById('instruction').value;
	var dwelling = document.getElementById('dwellingType').options[document.getElementById('dwellingType').selectedIndex].value;
	var status = document.getElementById('deliveryStatus').options[document.getElementById('deliveryStatus').selectedIndex].value;
	var building;
	var room;
	
	if (dwelling == 'Hotel' || dwelling == 'Apartment') {
		building = document.getElementById('building').value;
		room = document.getElementById('room').value;
	}
	else if (dwelling == 'Company Building') {
		building = document.getElementById('building').value;
		room = null;
	}
	else {
		building = null;
		room = null;
	}

	var valid = true;

	if (id == '') { //no item selected
		showDialog('No delivery is selected for updating.');
		return;
	}

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}/*
	else if (typeof(phone) != "number") {
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}*/
	else
		hideFieldMessage('phoneMessage');
		

	if (address == '') { //left blank
		valid = false;
		showFieldRequired('addressMessage');
	}
	else
		hideFieldMessage('addressMessage');
	
	if (city == '') { //left blank
		valid = false;
		showFieldRequired('cityMessage');
	}
	else
		hideFieldMessage('cityMessage');
	
	if (province == '') { //left blank
		valid = false;
		showFieldRequired('provinceMessage');
	}
	else
		hideFieldMessage('provinceMessage');

	if (dwelling == '') { //left blank
		valid = false;
		showFieldRequired('dwellingTypeMessage');
	}
	else
		hideFieldMessage('dwellingTypeMessage');

	if (valid)
		updateDeliverySend(id, firstname, lastname, phone, address, city,
				province, postalCode, dwelling, status, building, room, instruction);
}

//really done
function updateDeliverySend (id, firstname, lastname, phone, address, city,
		province, postalCode, dwelling, status, building, room, instruction) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('u') +
	            '&id=' + encodeURI(id) +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&address=' + encodeURI(address) +
	            '&city=' + encodeURI(city) +
	            '&province=' + encodeURI(province) +
	            '&postal=' + encodeURI(postalCode) +
	            '&dwelling=' + encodeURI(dwelling) +
	            '&building=' + encodeURI(building) +
	            '&room=' + encodeURI(room) +
	            '&status=' + encodeURI(status) +
	            '&instruction=' + encodeURI(instruction);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				updateDeliveryReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				updateDeliveryReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}


function updateDeliveryReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		listAllDeliverySend();
		showDialog('Delivery updated.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Update */


/* Delete */

function deleteDelivery () {
	openConfirmModalDialog('Please Confirm',
			'Are you sure you want to delete this delivery?','deleteDeliveryValidate');
}

function deleteDeliveryValidate () {
	var id = document.getElementById('deliveryID').value;
	if (id == '') {
		//no item selected
		showDialog('No delivery is selected for deletion.');
	} else {
		//item selected
		deleteDeliverySend(id);
	}
}


function deleteDeliverySend (id) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('d') +
	            '&id=' + encodeURI(id);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				deleteDeliveryReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				deleteDeliveryReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function deleteDeliveryReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		resetFields();
		listAllDeliverySend();
		showDialog('Delivery deleted.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Delete */


/* List All */

function listAllDelivery () {
	listAllDeliverySend();
}

function listAllDeliverySend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('l');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listAllDeliveryReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listAllDeliveryReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listAllDeliveryReceive (xml) {
	if (xml.getElementsByTagName('deliveries').length > 0) {
		var deliveries = xml.getElementsByTagName('deliveries')[0];
		showResults(buildTable(deliveries));
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10201)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List All */


/* List Dwelling Type */

function listDwellingType() {
	listDwellingTypeSend();
}

function listDwellingTypeSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('t');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listDwellingTypeReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listDwellingTypeReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function listDwellingTypeReceive (xml) {
	if (xml.getElementsByTagName('types').length > 0) {
		var types = xml.getElementsByTagName('types')[0];
		for (var loop = 0; loop < types.childNodes.length; loop++) {
			var type = types.childNodes[loop];
			var name = type.getElementsByTagName('name')[0].childNodes[0].nodeValue;
			var optgroup = document.getElementById('dwellingTypeOptGroup');
			var opt = document.createElement('option');
			opt.setAttribute('value', name);
			opt.innerHTML = name;
			optgroup.appendChild(opt);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10301)
			showDialog(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}


/* END List Dwelling Type */

/* List Delivery Status */

function listDeliveryStatus () {
	listDeliveryStatusSend();
}

function listDeliveryStatusSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('s');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listDeliveryStatusReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listDeliveryStatusReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listDeliveryStatusReceive (xml) {
	if (xml.getElementsByTagName('types').length > 0) {
		var types = xml.getElementsByTagName('types')[0];
		for (var loop = 0; loop < types.childNodes.length; loop++) {
			var type = types.childNodes[loop];
			var name = type.getElementsByTagName('name')[0].childNodes[0].nodeValue;
			var optgroup = document.getElementById('deliveryStatusOptGroup');
			var opt = document.createElement('option');
			opt.setAttribute('value', name);
			opt.innerHTML = name;
			optgroup.appendChild(opt);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10301)
			showDialog(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List Delivery Status */


/* Flag as complete */

function flagAsComplete (id) {
	// get of the info of delivery from hidden input
	var frm = document.getElementById('listDeliveryForm' + id);
	
	var firstname = frm.firstname.value;
	var lastname = frm.lastname.value;
	var phone = frm.phone.value;
	var address = frm.address.value;
	var city = frm.city.value;
	var province = frm.province.value;
	var pos = frm.postalCode.value;
	var dwelling = frm.dwelling.value;
	var room = frm.room.value;
	var building = frm.room.value;
	var status;
	if (frm.status.value != 'Done')
		status = 'Done';
	else
		status = 'Not Ready';
	var instruction = frm.instruction.value;
	
	// update the delivery with the status 'Done'
	updateDeliverySend (id, firstname, lastname, phone, address, city,
			province, pos, dwelling, status, building, room, instruction);
}

/* END Flag as complete */

/* Format check */

function isNumeric(strToCheck) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;

	if (strToCheck.length == 0) 
		return false;

	//  test strString consists of valid characters listed above
	for (var i = 0; i < strToCheck.length && blnResult; i++) {
	strChar = strToCheck.charAt(i);
   	if (strValidChars.indexOf(strChar) == -1)
	   blnResult = false;
	}
	return blnResult;
}

/* END Format check */